<template>
  <div class="dialog">
    <el-dialog :title="'清塘记录' + titleText" :visible.sync="showDialog" width="70%" top="0" :close-on-click-modal="false"
      @close="cancel">
      <el-form ref="ruleForm" label-position="left" :model="formData" :rules="rules" class="el-form">
        <el-form-item label="鱼塘名称:" prop="fishPondId" class="w50p">
          <el-select filterable clearable v-model="formData.fishPondId" @change="queryBatch">
            <el-option v-for="(item, index) in fishPondList" :key="index" :label="item.pondName"
              :value="item.fishPondId" />
          </el-select>
        </el-form-item>
        <el-form-item label="批次编号:" prop="productionBatchId" class="w50p">
          <el-select filterable clearable v-model="formData.productionBatchId" @change="batchChange">
            <el-option :disabled="!(item.closePondFlag)" v-for="(item, index) in batchList" :key="index"
              :label="`${item.pondName}__(批次：${item.mnecode})__${item.varietyName}【${item.num}】尾__该批次${!(item.closePondFlag) ? '不可' : '可'}清塘`"
              :value="item.productionBatchId" />
          </el-select>
        </el-form-item>
        <el-form-item label="清塘人:" prop="staffId" class="w50p">
          <el-select filterable clearable disabled v-model="formData.staffName" @change="selectStaff">
            <el-option v-for="(item, index) in staffList" :key="index" :label="item.staffName"
              :value="item.staffId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="清塘日期:" prop="clearDate" class="w50p">
          <el-date-picker v-model="formData.clearDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" clearable
            :picker-options="pickerOptions" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import ClearPondManageApi from "@/api/clear-pond-manage"
import BatchMangeApi from "@/api/batch-mange"
import { dialogMixin } from "@/utils/dialogMixin";
let maxTime = null
export default {
  name: '',
  components: {},
  mixins: [dialogMixin],
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {}
      }
    },
    staffList: {
      type: [Array],
      default: () => {
        return []
      }
    },
    fishPondList: {
      type: [Array],
      default: () => {
        return []
      }
    },
  },
  data() {
    let checkInt = (rule, value, callback) => {
      if (value) {
        if (Number(value) && value % 1 === 0) {
          callback();
        } else {
          return callback(new Error("请输入整数！"));
        }
      }
    };
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date(new Date(maxTime).getTime(new Date(maxTime))) || time.getTime() > new Date().getTime();
        },

        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            if (maxTime < date.getTime() - 3600 * 1000 * 24) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            if (maxTime < date.getTime() - 3600 * 1000 * 24 * 7) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }],
      },
      rules: {
        fishPondId: [
          { required: true, message: "请选择鱼塘", trigger: ["change", "blur"] }
        ],
        productionBatchId: [
          { required: true, message: "请选择批次", trigger: ["change", "blur"] }
        ],
        staffName: [
          { required: true, message: "请选择清塘人", trigger: ["change", "blur"] },
        ],
        clearDate: [
          { required: true, message: "请选择清塘日期", trigger: ["change", "blur"] },
        ],
      },
      fishNum: 0,
      formData: {},
      batchList: [],
      showDialog: this.show
    };
  },
  computed: {
  },
  watch: {
    show(v) {
      maxTime = null
      this.showDialog = v;
    },
    nowChanceStau(v) {
      if (v === 'add') {
        this.getSelectBatch()
        this.$nextTick(() => {
          let staffName = sessionStorage.getItem("staffName")
          let staffId = sessionStorage.getItem("staffId")
          let userList = this.staffList.filter(item => {
            return Number(item.staffId) === Number(staffId)
          })
          this.formData = {
            // staffId: sessionStorage.getItem('staffId'),
            // staffName: sessionStorage.getItem('staffName'),
            staffName: userList.length == 0 ? this.staffList[0].staffName : staffName,
            staffId: userList.length == 0 ? this.staffList[0].staffId : Number(staffId),
            clearDate: this.getNowTime()
          }
          if (this.formData.staffId == 1) {
            this.formData.staffName = this.staffList[0].staffName
            this.formData.staffId = this.staffList[0].staffId
          }
          this.$refs['ruleForm'].resetFields()
        })
      }
      if (v === 'edit') {
        this.formData = this.editObject
        BatchMangeApi.queryByCondition({}).then(res => {
          this.batchList = res.data;
        })
      }
    }
  },
  created() {
    maxTime = null
  },
  mounted() {
  },
  methods: {
    batchChange(e) {
      maxTime = ''
      this.formData.clearDate = new Date()
      this.batchList.find(item => {
        if (item.productionBatchId === e) {
          this.formData.fishPondId = item.fishPondId;
          maxTime = new Date(item.buildDateTime)
          this.fishNum = item.num || 0;
          // this.formData.clearDate = this.formatDateTimeMHS(maxTime)
        }
      })
    },
    getSelectBatch() {
      BatchMangeApi.queryByCondition({ status: 'UN_COMPLETE' }).then(res => {
        this.batchList = res.data;
      })
    },
    //查询可选批次
    queryBatch(e) {
      this.$set(this.formData, 'productionBatchId', undefined)
      BatchMangeApi.queryByCondition({ fishPondId: e, status: 'UN_COMPLETE' }).then(res => {
        this.batchList = res.data;
      })
    },
    // batchChange (e) {
    //   this.batchList.find((item) => {
    //     if (item.productionBatchId === e) {
    //       this.formData.fishPondId = item.fishPondId;
    //       return true
    //     }
    //   })
    // },
    saveData(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            ClearPondManageApi.edit(this.formData).then(res => {
              if (res.success === true) {
                this.$message.success("修改成功！");
                this.close()
              } else {
                this.$message.error(res.message);
              }
            });
          } else if (this.nowChanceStau === "add") {
            ClearPondManageApi.add(this.formData).then(res => {
              if (res.success === true) {
                this.$message.success("添加成功！");
                this.close()
              } else {
                this.$message.error(res.message);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    save(formData) {
      console.log(this.fishNum)
      debugger
      if (Number(this.fishNum) > 0) {
        this.$confirm(`该批次还有${this.fishNum}尾,是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.saveData(formData)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      } else {
        this.saveData(formData)
      }
    },
    close() {
      this.$emit("closeDialog");
    },
    cancel() {
      this.$emit("cancelDialog");
    },
    selectStaff(e) {
      this.formData.staffName = this.staffList.filter(item => item.staffId == e)[0].staffName
    }
  }
};
</script>

<style lang="scss" scoped></style>
